<template>
    <div class="app-container">
        <el-form ref="form" :model="paperForm" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="题库名称" prop="questionBankName">
                        <el-select v-model="paperForm.questionBankName" value-key="questionBankId" placeholder="请选择题库" filterable size="small" style="width: 100%;"
                                   @change="function(q) {return bindData(q)}" :disabled="paperForm.paperId != undefined ? true : false">
                            <el-option
                                    v-for="q in questionBankListOptions"
                                    :key="q.questionBankId"
                                    :label="q.questionBankName"
                                    :value="q"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="项目代码" prop="projectCode">
                        <el-input v-model="paperForm.projectCode" size="small" width :disabled="true"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="建议时长" prop="suggestTime">
                        <el-input v-model="paperForm.suggestTime" size="small" width />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="试卷名称"  prop="paperName">
                        <el-input v-model="paperForm.paperName" size="small"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="试卷状态" prop="paperStatus">
                        <el-radio-group ref="paperStatus" v-model="paperForm.paperStatus">
                            <el-radio
                                    v-for="dict in paperStatusList"
                                    :key="dict.code"
                                    :label="dict.code"
                            >{{ dict.name }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-divider></el-divider>
<!--           试题搜索区域  -->
            <el-row>
                <el-col :span="24">
                    <div align="center" style="margin-bottom: 5px;">
                        <b style="font-size: 15px;font-family: 宋体;align-content: center;">试卷试题添加区域</b>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="试题类型" prop="questionType">
                        <el-select v-model="queryParams.questionType" placeholder="试题类型" clearable size="small" style="width: 100%;">
                            <el-option v-for="dict in questionTypeOptions"
                                       :key="dict.code"
                                       :label="dict.name"
                                       :value="dict.code"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="试题题干" prop="questionStems">
                        <el-input v-model="queryParams.questionStems" placeholder="请输入试题题干" clearable size="small"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item style="margin-left: -70px;">
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" style="margin-left:10px;">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
<!--    试题穿梭框    -->
        <div>
            <el-row :gutter="24" class="condition-table">
                <!-- 左侧 题库试题 -->
                <el-col :span="11" style="padding-left:0">
                    <div class="no-add">
                        <span style="padding-left: 15px;">题库试题</span>
                    </div>
                    <el-table ref="selectedQuestionTable" :row-key="getRowKeys" max-height="300" border v-loading="leftLoading" :data="questionList"
                              @selection-change="handleQuestionChange" @row-click="goQuestionRowClick" :header-cell-style="{background:'#f5f8ff'}">
                        <el-table-column type="selection" align="center" :reserve-selection="true" width="50"></el-table-column>
                        <el-table-column label="类型" align="center" prop="questionType"  width="80" :formatter="questionTypeFormat"/>
                        <el-table-column label="题干" align="center" prop="questionStems" :formatter="highlight" :show-overflow-tooltip="true">
                            <!--<template slot-scope="scope">
                                <div v-html="scope.row.questionStems"></div>
                            </template>-->
                        </el-table-column>
                    </el-table>
                    <pagination
                            v-show="total>0"
                            :total="total"
                            :pager-count=5
                            layout="total, prev, pager, next"
                            :page.sync="pageParams.page"
                            :limit.sync="pageParams.rows"
                            @pagination="getList"
                    />
                </el-col>
                <!-- 左右穿梭图标 -->
                <el-col :span="2">
                    <div style="margin-top: 200px;">
                        <p class="icon-right-if icon-return" @click="handleAddPaperQuestion" v-if="questionList.length>0">
                            <i class="el-icon-arrow-right"></i>
                        </p>
                        <p class="icon-right-else icon-return" v-else>
                            <i class="el-icon-arrow-right"></i>
                        </p>
                        <p class="icon-right-if" @click="handleAddQuestion" v-if="paperForm.questionCopyDTOList.length > 0">
                            <i class="el-icon-arrow-left"></i>
                        </p>
                        <p class="icon-right-else" v-else>
                            <i class="el-icon-arrow-left"></i>
                        </p>
                    </div>
                </el-col>
                <!-- 右侧试卷试题 -->
                <el-col :span="11" style="padding-right:0">
                    <div class="no-add">
                        <span>试卷试题</span>
                        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
                                   @click="handleDlePaperQuestion"
                        >删除</el-button>
                    </div>
                    <el-table ref="selectedPaperQuestionTable" :row-key="getRowKeys" border max-height="300" v-loading="rightLoading" :data="paperForm.questionCopyDTOList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                              @selection-change="handleSelectedPaperQuestionChange"  @row-click="goPaperRowClick" :header-cell-style="{background:'#f5f8ff'}">
                        <el-table-column type="selection" align="center" :reserve-selection="true" width="50"></el-table-column>
                        <el-table-column label="类型" align="center"  prop="questionType" :formatter="questionTypeFormat" width="80" :show-overflow-tooltip="true" />
                        <el-table-column label="题干" align="center" prop="questionStems" :formatter="highlight"  :show-overflow-tooltip="true">
                            <!--<template slot-scope="scope">
                                <div v-html="scope.row.questionStems"></div>
                            </template>-->
                        </el-table-column>
                    </el-table>
                    <pagination
                            v-show="paperForm.questionCopyDTOList.length > 0"
                            :total="paperForm.questionCopyDTOList.length"
                            :page.sync="currentPage"
                            :limit.sync="pageSize"
                            :pager-count=5
                            layout="total, prev, pager, next"
                    />
                </el-col>
            </el-row>
        </div>
        <el-divider></el-divider>
        <div slot="footer" align="center" class="dialog-footer" style="float: right;">
            <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">保 存</el-button>
            <el-button :loading="buttonLoading" size="mini" @click="cancel">取 消</el-button>
        </div>
    </div>
</template>

<script>
    import {listQuestionBank} from "@/api/question/questionBank";
    import {addExamPaper, updateExamPaper,} from "@/api/question/paper";
    import {getQuestionByQuestionId, listQuestion} from "@/api/question/question";
    export default {
        name: "paperForm",
        props: {
            // 试卷表单信息
            paperForm: Object,
            // 试卷状态信息
            paperStatusList: Array
        },
        data() {
            return {
                //题库信息
                questionBankListOptions: [],
                //试题类型
                questionTypeOptions: [],
                // 非多个禁用
                multiple: true,
                // 试题总条数
                total: 0,
                // 试题表格数据
                questionList: [],
                // 选中试题集合
                pitchQuestionList: [],
                // 选中试卷试题集合
                pitchPaperQuestionList: [],
                // 提交按钮控制
                buttonLoading: false,
                // 试题分页参数
                pageParams: {
                    page: 1,
                    rows: 10,
                },
                // 试卷试题分页
                currentPage: 1,
                pageSize: 10,
                // 查询试题参数
                queryParams: {
                    // 题库Id
                    questionBankId: undefined,
                    // 题干
                    questionStems: undefined,
                    // 试题类型
                    questionType: undefined,
                },
                rules: {
                    questionBankName: {required: true, message: "题库不能为空", trigger: "blur"},
                    paperName: {required: true, message: "试卷名称不能为空", trigger: "blur"},
                    paperStatus: {required: true, message: "试卷状态不能为空", trigger: "blur"},
                },
                // 左侧加载
                leftLoading: false,
                // 右侧加载
                rightLoading: false,
            }
        },
        created() {
            //题库信息
            listQuestionBank({
                'pageParameter': {page: 1, rows: 1000},
                'searchParams': {}
            }).then(response => {
                this.questionBankListOptions = response.responseBody.result;
            });
            //试题类型
            this.getDicts("question_type").then(response => {
                this.questionTypeOptions = response.responseBody.result;
            })
        //    获取题库所属试题
            this.handleQuery();
        },
        methods:{
            //绑定相关数据
            bindData(q) {
                this.paperForm.projectCode = q.projectCode;
                this.paperForm.projectName = q.projectName;
                this.paperForm.questionBankId = q.questionBankId;
                this.paperForm.questionBankName = q.questionBankName;
                // this.paperForm.paperScore = q.theoryTotal; // 卷面分不需要
                this.paperForm.suggestTime = q.theoryDuration;
                // 重置试卷试题
                this.paperForm.questionCopyDTOList = [];
                //    获取题库所属试题
                this.handleQuery();
            },
            // 将左边表格选择项存入pitchQuestionList中(后面与右边的对比，右边已存在不添加)
            handleQuestionChange(selection) {
                this.pitchQuestionList = selection.map(item => item)
            },
            // 将右边表格选择项存入pitchPaperQuestionList中
            handleSelectedPaperQuestionChange(selection) {
                this.pitchPaperQuestionList = selection.map(item => item)
                this.multiple = !selection.length
            },
            // 点击题库试题某一行,添加到试卷试题中
            goQuestionRowClick(row, column, event) {
                let repeat = false;
                //选中题库试题Id
                var pitchQuestionId = row.questionId;
                // 检查重复试卷试题
                for (let j = 0; j < this.paperForm.questionCopyDTOList.length; j++) {
                    var questionId = this.paperForm.questionCopyDTOList[j].questionId;
                    if (pitchQuestionId === questionId) { // 重复试卷试题
                        //    清除试卷试题中重复的试题
                        this.paperForm.questionCopyDTOList.splice(j,1);
                    }
                }
                //试卷没有重复试题，进行临时保存
                if (!repeat) {
                    this.rightLoading = true;
                    // 通过试题ID获取试题详细信息及选项
                    getQuestionByQuestionId(pitchQuestionId).then(response => {
                        if (response.responseBody === null) {
                            //题库未找到'+question.questionStems+'试题，
                            const h = this.$createElement
                            this.$confirm('提示', {
                                title: '提示',
                                message: h('div', [
                                    h('p', '该题原来属于试卷试题！, 是否继续添加?'),
                                    h('p',{style:'fontSize:10px;'}, '(题库试题刷新后，该试题不保留！)')
                                ]),
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }).then(() => { // 添加
                                this.paperForm.questionCopyDTOList.push(row);
                            }).catch(() => {});
                            return;
                        }
                        const questionInfo = response.responseBody;
                        this.paperForm.questionCopyDTOList.push(questionInfo);
                    });
                    this.rightLoading = false;
                }
            },
            // 添加到题库试题中
            goPaperRowClick(row, column, event) {
                let repeat = false;
                //选中试卷试题Id
                var pitchQuestionId = row.questionId;
                // 检查重复试题
                for (let j = 0; j < this.questionList.length; j++) {
                    var questionId = this.questionList[j].questionId;
                    if (pitchQuestionId === questionId) { // 重复题库试题
                        //    临时移除题库试题
                        this.questionList.splice(j,1);
                    }
                }
                //题库没有重复试题，进行临时保存
                if (!repeat) {
                    // 添加到题库试题中（前端临时保存）
                    this.questionList.push(row);
                    // 移除已选中的试卷试题
                    for (let j = 0; j < this.paperForm.questionCopyDTOList.length; j++) {
                        var questionId = this.paperForm.questionCopyDTOList[j].questionId;
                        if (pitchQuestionId === questionId) { // 移除选中试卷试题
                            this.paperForm.questionCopyDTOList.splice(j,1);
                        }
                    }
                }
            },
            // 添加到试卷试题当中
            handleAddPaperQuestion() {
                let repeat = false;
                var length = this.pitchQuestionList.length;
                for (let i = 0; i < length; i++) {
                    var pitchQuestionId = this.pitchQuestionList[i].questionId;
                    // 检查重复试卷试题
                    if (this.paperForm.questionCopyDTOList.length > 0) {
                        for (let j = 0; j < this.paperForm.questionCopyDTOList.length; j++) {
                            var questionId = this.paperForm.questionCopyDTOList[j].questionId;
                            if (pitchQuestionId === questionId) { // 重复试卷试题
                            //    清除试卷试题中重复的试题
                                this.paperForm.questionCopyDTOList.splice(j,1);
                            }
                        }
                    }
                }
                //试卷没有重复试题，进行临时保存
                if (!repeat) {
                    this.rightLoading = true;
                    // 遍历选中试题项
                    this.pitchQuestionList.forEach(question => {
                        var pitchQuestionId = question.questionId;
                        // 通过试题ID获取试题详细信息及选项
                        getQuestionByQuestionId(pitchQuestionId).then(response => {
                            if (response.responseBody === null) {
                                //题库未找到'+question.questionStems+'试题，
                                const h = this.$createElement
                                this.$confirm('提示', {
                                    title: '提示',
                                    message: h('div', [
                                        h('p', '该题原来属于试卷试题！, 是否继续添加?'),
                                        h('p',{style:'fontSize:10px;'}, '(题库试题刷新后，该试题不保留！)')
                                    ]),
                                    confirmButtonText: '确定',
                                    cancelButtonText: '取消',
                                    type: 'warning'
                                }).then(() => { // 添加
                                    this.paperForm.questionCopyDTOList.push(question);
                                }).catch(() => {});
                                return;
                            }
                            const questionInfo = response.responseBody;
                            this.paperForm.questionCopyDTOList.push(questionInfo);
                        });
                    })
                    // 清空左边选中项
                    this.$refs.selectedQuestionTable.clearSelection();
                    this.rightLoading = false;
                }
            },
//          添加到题库试题中
            handleAddQuestion() {
                let repeat = false;
                var length = this.pitchPaperQuestionList.length;
                for (let i = 0; i < length; i++) {
                    var pitchQuestionId = this.pitchPaperQuestionList[i].questionId;
                    // 检查重复试题
                    for (let j = 0; j < this.questionList.length; j++) {
                        var questionId = this.questionList[j].questionId;
                        if (pitchQuestionId === questionId) { // 重复题库试题
                        //    临时移除题库试题
                            this.questionList.splice(j,1);
                        }
                    }
                }
                //题库没有重复试题，进行临时保存
                if (!repeat) {
                    this.pitchPaperQuestionList.forEach(question => {
                        // 添加到题库试题中（前端临时保存）
                        this.questionList.push(question);
                    })
                    // 移除已选中的试卷试题
                    this.handleDlePaperQuestion();
                }
            },
//          移除选中试卷试题
            handleDlePaperQuestion() {
                var length = this.pitchPaperQuestionList.length;
                for (let i = 0; i < length; i++) {
                    var pitchQuestionId = this.pitchPaperQuestionList[i].questionId;
                    // 检查删除掉重复试题
                    for (let j = 0; j < this.paperForm.questionCopyDTOList.length; j++) {
                        var questionId = this.paperForm.questionCopyDTOList[j].questionId;
                        if (pitchQuestionId === questionId) { // 移除重复试卷试题
                            this.paperForm.questionCopyDTOList.splice(j,1);
                        }
                    }
                }
                // 清空右边选中项
                this.$refs.selectedPaperQuestionTable.clearSelection();
            },
            /** 查询试题列表 */
            getList() {
                this.leftLoading = true;
                listQuestion({
                    'pageParameter': this.pageParams,
                    'searchParams': this.queryParams
                }).then(response => {
                    this.questionList = response.responseBody.result;
                    this.total = response.responseBody.pageParameter.totalCount;
                    this.leftLoading = false;
                });
            },
            /** 重置试题搜索按钮操作 */
            resetQuery() {
                this.queryParams.questionStems = undefined;
                this.queryParams.questionType = undefined;
                this.handleQuery();
            },
            /** 搜索按钮操作 */
            handleQuery() {
                // 查询题库试题所需题库参数
                this.queryParams.questionBankId = this.paperForm.questionBankId;
                this.pageParams.pageNum = 1;
                if (this.queryParams.questionBankId === undefined) {
                    return this.msgWarning("请选择题库！");
                }
                this.getList();
            },
            // 试题类型字典翻译
            questionTypeFormat(row, column) {
                return this.selectDictLabel(this.questionTypeOptions, row.questionType);
            },
            // 去掉所有的html标记
            highlight (row,column) {
                return row.questionStems.replace(/<[^>]+>/g, '');
            },
            //新增
            submitForm(){
                this.$refs["form"].validate(valid => {
                    if(valid){
                        this.buttonLoading = true;
                        if(this.paperForm.paperId != undefined){
                            updateExamPaper(this.paperForm).then(response => {
                                if (response.retCode === '200') {
                                    if (response.responseBody === 1) {
                                        this.msgSuccess(response.message);
                                        this.$emit("submitForm");
                                        this.$emit("cancelDialog");
                                    } else {
                                        this.msgWarning(response.message);
                                    }
                                }
                            }).finally(() => {
                                this.buttonLoading = false;
                            });
                        }else {
                            addExamPaper(this.paperForm).then(response => {
                                if (response.retCode === '200') {
                                    if (response.responseBody === 1) {
                                        this.msgSuccess(response.message);
                                        this.$emit("submitForm");
                                        this.$emit("cancelDialog");
                                    } else {
                                        this.msgWarning(response.message);
                                    }
                                }
                            }).finally(() => {
                                this.buttonLoading = false;
                            });
                        }
                    }
                });
            },
            getRowKeys(row) {
                return row.questionId;
            },
            cancel(){
                this.$emit("cancelDialog");
            },
        }
    }
</script>

<style scoped >
    .el-icon-arrow-left {
        font-size: 21px !important;
        background: #d9d9d9;
        border-radius: 4px;
        color: #fff;
        padding: 2px;
    }
    .el-icon-arrow-right {
        font-size: 21px !important;
        background: #d9d9d9;
        border-radius: 4px;
        color: #fff;
        padding: 2px;
    }
    /deep/ .el-popover__reference-wrapper {
        vertical-align: middle !important;
        padding-left: 4px;
    }
    .icon-right-if .el-icon-arrow-left {
        background: #409eff;
        color: #fff;
    }
    .icon-right-if .el-icon-arrow-right {
        background: #409eff;
        color: #fff;
    }
    .icon-center {
        i {
            margin-top: 8px;
            :hover {
                cursor: pointer;
            }
        }
        .icon-return {
            transform: rotate(180deg);
        }
    }
    .no-add {
        display: flex;
        justify-content: space-between;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        margin-bottom: 10px;
        span {
            color: #333;
        }
    }
</style>
